<template>
  <div class="clearfix" style="display: inline-block">
    <el-tree
      :data="directories"
      node-key="id"
      default-expand-all
      accordion
      :props="{ children: 'children', label: 'name' }"
      :expand-on-click-node="false"
      :highlight-current="true"
      :current-node-key="directory_id"
      @node-click="handleNodeClick"
    >
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <span :class="{ 'selected-node': data.id === directory_id }">
          <i :class="data.id === directory_id ? 'el-icon-folder-opened' : 'el-icon-folder'" />
          {{ node.label }}
        </span>
        <span>
          <el-button
            type="text"
            size="mini"
            icon="el-icon-plus"
            style="color: green"
            @click.stop="() => append(data)"
          />
          <el-button
            type="text"
            size="mini"
            style="color: red"
            title="删除目录"
            icon="el-icon-delete"
            @click.stop="() => remove(node, data)"
          />
        </span>
      </span>
    </el-tree>
    <!-- 新增目录表单 -->
    <div class="directory-form">
      <el-button type="text" size="mini" @click="handleAddDrectory('')">
        添加目录
      </el-button>
    </div>
  </div>
</template>

<script>
import {
  Post as AddDirectory,
  Delete as DeleteDirectory,
  GetTree
} from '@/api/crm/crmdirectory'

export default {
  name: 'Crmdirectoryselector',
  props: ['id', 'name'],
  data() {
    return {
      directory_name: '',
      directory_id: '',
      treeLoading: false,
      directories: []
    }
  },
  created() {
    this.handleFetchTree()
  },
  mounted() {
    const lastSelectedDirectory = localStorage.getItem('lastSelectedDirectory')
    if (lastSelectedDirectory) {
      this.directory_id = parseInt(lastSelectedDirectory)
      this.handleChangeNode(this.directory_id)
    }
  },
  methods: {
    append(data) {
      this.handleAddDrectory(data.id)
    },
    remove(node, data) {
      this.handleDelete(data)
    },
    handleDelete(data) {
      this.$confirm(`确认要删除目录  ${data.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.treeLoading = true
        DeleteDirectory(data.id)
          .then(response => {
            this.handleFetchTree()
          })
          .catch(() => {
            this.treeLoading = false
          })
      }).catch(() => {
      })
    },
    handleAddDrectory(parent_id) {
      let promptTitle = '请输入目录名称'
      if (parent_id) {
        promptTitle = '请输入子目录名称'
      } else {
        promptTitle = '请输入目录名称'
      }
      this.$prompt(promptTitle, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        AddDirectory({ name: value, parent_id: parent_id })
          .then(response => {
            this.handleFetchTree()
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    handleNodeClick(data) {
      this.directory_id = data.id // 触发 Vue 的响应式更新
      this.$emit('change', { id: data.id.toString(), name: data.name })
      // 保存选择的目录到 localStorage
      localStorage.setItem('lastSelectedDirectory', data.id)
    },
    handleChangeNode(value) {
      const findNameById = (directories, id) => {
        for (const directory of directories) {
          if (directory.id === id) {
            return directory.name
          }
          if (directory.children) {
            const result = findNameById(directory.children, id)
            if (result) return result
          }
        }
        return null
      }
      this.directory_name = findNameById(this.directories, this.directory_id)
      this.$emit('change', { id: this.directory_id, name: this.directory_name })
    },
    handleFetchTree() {
      this.treeLoading = true
      GetTree()
        .then(response => {
          this.directories = response.data
          this.treeLoading = false
          // 读取 localStorage 中保存的目录 ID 并设置为当前选中
          const lastSelectedDirectory = localStorage.getItem('lastSelectedDirectory')
          if (lastSelectedDirectory) {
            this.directory_id = parseInt(lastSelectedDirectory)
            this.handleChangeNode(this.directory_id)
          }
        })
        .catch(e => {
          this.treeLoading = false
        })
    },
    handleClickNode(data) {
      this.$emit('handleClickNode', data)
    }
  }
}
</script>

<style scoped>
.custom-tree-node button {
  margin-left: 4px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: 100%;
}

.clearfix ::after {
  content: "";
  display: block;
  clear: both;
}

/* 新增样式 */
.selected-node {
  color: #409EFF !important;
  font-weight: bold !important;
}

.el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f7ff !important;
}
</style>
